package cn.tl.user.controller;

import cn.tl.base.exception.BusinessException;
import cn.tl.org.utils.AjaxResult;
import cn.tl.user.domain.LoginInfo;
import cn.tl.user.domain.User;
import cn.tl.user.domain.dto.UserDto;
import cn.tl.user.service.ILoginInfoService;
import cn.tl.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ILoginInfoService loginInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/verifyPhone")
    public AjaxResult verifyPhone(@RequestBody User user){
        //根据手机号查询表
        User byPhone = userService.findByPhone(user.getPhone());
        if(byPhone == null){
            return AjaxResult.me();
        }else {
            return AjaxResult.me().setMessage("手机号被注册");
        }

    }
    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserDto userDto) {
        System.out.println(userDto);
        try {
            LoginInfo loginInfo = loginInfoService.login(userDto);
            //生成token
            String token = UUID.randomUUID().toString();
            //放入redis里面
            redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            map.put("loginInfo", loginInfo);
            return AjaxResult.me().setResultObj(map);
        } catch (BusinessException e) {
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }
}
